"use strict";

// ym2 web component (自定义组件)
!function ( top, global, ym2App ) {
    //环境
    var YM_ENV_DEV = true;
    var ym2 = global.ym2;
    var setTimeout = global.setTimeout;
    var topLayer = top.layer;
    var topJquery = top.jQuery;
    var topSpinner = top.ymSpinner;
    var topSwal = top.SweetAlert;
    var HTTP_SUCCESS_CODE = ym2.getHttpSuccessCode();
    var HTTP_FAILURE_CODE = ym2.getHttpFailureCode();
    var HTTP_UNAUTHORIZED_CODE = ym2.getHttpUnauthorizedCode();
    var HTTP_AJAX_IDENTITY = ym2.getHttpAjaxIdentity();
    var ADMIN_LOGIN_PAGE_URL = ym2.getAdminRouteLogin();
    var YM_APP_THEME_COLOR = ym2.getAppThemeColor();

    //调试打印
    function debug_dump() {
        if (!YM_ENV_DEV) {
            return;
        }
        for (var i = 0; i < arguments.length; i++) {
            console.log(arguments[i]);
        }
    }

    //空函数
    function noop() {

    }

    //抛出异常
    function throw_error(errors) {
        throw errors;
    }

    //基础功能对象
    function base_utils( $http ) {
        var utils = {

            //自动识别场景分发。
            autoDispatch: function ( params, scope ) {
                return utils[ params.type.toLowerCase() ].call( this, params, scope );
            },

            /**
             * 实现modal
             * @param params
             * - url 链接地址
             * - modalTitle 标题
             * - width 宽 px
             * - height 高 px
             * - closeBtn 是否底部关闭 1：是 0：否
             * - _requestParams 请求参数
             * @param scope angular作用域
             */
            modal: function ( params, scope ) {
                var opts = {
                    url: params.url || throw_error("模态框url未定义。"),
                    modalTitle: params.modalTitle || " ",
                    width: params.width || "620px",
                    height: params.height || "750px",
                    closeBtn: Number( params.closeBtn ) === 1,
                    modalCloseCallback: params.modalCloseCallback,
                    refererWindow: params.refererWindow,
                    _requestParams: params._requestParams,
                };
                var layerScreenObj = ym2.layerScreenOptions( opts.width );
                var refererName = ym2.layerRefererWindowName( opts.refererWindow );

                var activeIndex = topLayer.index;
                var layerCf = {
                    type: 2,
                    area: [ layerScreenObj.width, opts.height ],
                    title: opts.modalTitle,
                    shade: 0.3,
                    shadeClose: false,
                    //maxmin: true,
                    anim: 0,
                    scrollbar: false,
                    content: ym2.addUrlQueryParam( opts.url, opts._requestParams ),
                    success: function( layero, index, that ){
                        //关闭spinner
                        // topSpinner.hide( loadingFlag );

                        //获取iframe的窗口对象，添加来源追踪。
                        var iframeWin = top[ layero.find( "iframe" )[0][ "name" ] ];
                        iframeWin.__REFERER_WIN_NAME = refererName;

                        //键盘事件关闭
                        topJquery( ".ym2_kc_" + activeIndex ).focus().on("keydown", function (e) {
                            // 空格和回车键
                            if (e.keyCode === 13 || e.keyCode === 32) {
                                topJquery( this ).trigger( "click" );
                            }
                        });

                    },
                };

                //底部确定
                if ( opts.closeBtn ) {
                    layerCf.btn = [ `<span class="ym2_keydown_close ym2_kc_${activeIndex}" tabindex="0">关闭</span>` ];
                    if ( opts.modalCloseCallback ) {
                        layerCf.btn1 = function ( index, layero, that ) {
                            eval( opts.modalCloseCallback );
                            topLayer.close( index );
                            return false;
                        };
                    }
                }

                //标题栏关闭
                if ( opts.modalCloseCallback ) {
                    layerCf.cancel = function ( index, layero, that ) {
                        eval( opts.modalCloseCallback );
                        topLayer.close( index );
                        return false;
                    }
                }

                // var loadingFlag = topSpinner.show("请稍后...");
                topLayer.open( layerCf );

            },

            /**
             * 实现单页
             * @param params
             * - url 链接
             * - frame 视图窗口 self、top、parent
             * - target 目标，_blank、_self、_parent、_top
             * - _requestParams 请求参数
             * @param scope angular作用域
             */
            page: function ( params, scope ) {
                var opts = {
                    url: params.url || throw_error( "模态框url未定义。" ),
                    frame: params.frame === "top" ? top : ( params.frame === "parent" ? parent : self ),
                    target: params.target || "_self",
                    _requestParams: params._requestParams,
                };

                // 打开
                opts.frame.open( ym2.addUrlQueryParam( opts.url, opts._requestParams ), opts.target );
            },

            /**
             * 实现ajax调用
             * @param params
             * - url 链接
             * - method http动作 GET、POST
             * - questionTitle 询问标题
             * - questionDescription 询问描述
             * - ajaxSuccessCallback ajax返回成功回调
             * - ajaxFailureCallback ajax返回失败回调
             * - _requestParams 请求参数
             * @param scope angular作用域
             */
            ajax: function ( params, scope ) {
                var opts = {
                    url: params.url || throw_error( "模态框url未定义。" ),
                    method: params.method.toUpperCase(),
                    questionTitle: params.questionTitle || "",
                    questionDescription: params.questionDescription || "请问，您确定要执行该操作吗？",
                    ajaxSuccessCallback: params.ajaxSuccessCallback,
                    ajaxFailureCallback: params.ajaxFailureCallback,
                    _requestParams: params._requestParams,
                };

                ym2.swal.question(topSwal, opts.questionTitle, opts.questionDescription, function ( result ) {
                    /* Read more about isConfirmed, isDenied below */
                    if ( result.isConfirmed ) {
                        // request
                        var instance;
                        var params = opts._requestParams;
                        params[ HTTP_AJAX_IDENTITY ] = 1;

                        if ( opts.method === "GET" ) {
                            instance = $http.get( ym2.addUrlQueryParam( opts.url, params ) );
                        } else if ( opts.method === "POST" ) {
                            instance = $http.post( opts.url, params );
                        }

                        // show loading
                        var flag = topSpinner.show();
                        instance.then(function (result) {
                            topSpinner.hide( flag );

                            var data = result.data;
                            switch ( data.code ) {
                                case HTTP_SUCCESS_CODE:
                                    ym2.swal.ok( topSwal, data.msg );
                                    if ( opts.ajaxSuccessCallback ) {
                                        eval( opts.ajaxSuccessCallback );
                                    }
                                    break;
                                case HTTP_FAILURE_CODE:
                                    ym2.swal.fail(topSwal, data.msg);
                                    if ( opts.ajaxFailureCallback ) {
                                        eval( opts.ajaxFailureCallback );
                                    }
                                    break;
                                case HTTP_UNAUTHORIZED_CODE:
                                    ym2.swal.timer(
                                        topSwal,
                                        data.msg,
                                        `自动跳转; <a href="${ADMIN_LOGIN_PAGE_URL}" target="_top">立即跳转<a/>`,
                                        function () {
                                            top.open(ADMIN_LOGIN_PAGE_URL, "_self");
                                        },
                                        3000
                                    );

                                    break;
                                default:
                                    ym2.swal.fail(topSwal, data.msg);
                            }

                        }, function (error) {
                            topSpinner.hide(flag);
                            ym2.swal.fail( topSwal, error.data || "系统错误,发起请求失败!" );
                            debug_dump( error );
                        });

                    }
                });

            },
        };

        return utils;
    }

    ym2App.directive("ngxBlock", ["$http", function ( $http ) {
        /**
         * 动态按钮：支持modal、page、ajax 三种场景。
         * @see builder/test/controllers/CompController.php
         */
        return {
            restrict: "E",
            replace: true,
            transclude: true, //相当于slot
            template: `<div ng-click="dispatchEvent()" ng-transclude></div>`,
            scope: true,
            compile: function (element, attribute) {
                return {
                    post: function (scope, element, attribute, controller, transclude) {
                        //debug_dump( scope, element, attribute, controller, transclude );
                        var utils = base_utils( $http );
                        var options = {
                            type: attribute.type,//场景：modal、ajax、page
                            url: attribute.url,//all：链接地址
                            modalTitle: attribute.modalTitle,//modal：标题
                            width: attribute.width,//modal：宽
                            height: attribute.height,//modal：高
                            closeBtn: attribute.closeBtn,//modal：是否底部关闭
                            modalCloseCallback: attribute.modalCloseCallback,//modal：关闭回调
                            refererWindow: attribute.refererWindow,//modal：iframe来源窗口
                            target: attribute.target,//page：目标
                            frame: attribute.frame,//page：视图窗口
                            method: attribute.method,//ajax：http动作
                            questionTitle: attribute.questionTitle,//ajax：询问标题
                            questionDescription: attribute.questionDescription,//ajax：询问描述
                            ajaxSuccessCallback: attribute.ajaxSuccessCallback,//ajax：成功回调
                            ajaxFailureCallback: attribute.ajaxFailureCallback,//ajax：失败回调
                        };
                        var scopeParams;
                        if ( attribute.scope ) {
                            try {
                                scopeParams = JSON.parse( attribute.scope );
                            }
                            catch {
                                scopeParams = {};
                                console.error( "attribute.scope值JSON解析错误。" );
                            }
                        } else {
                            scopeParams = {};
                        }

                        scope.dispatchEvent = function () {
                            var requestParams = {};
                            var vv;
                            for (var key in scopeParams) {
                                try {
                                    vv = scope.$eval( scopeParams[ key ] );
                                }
                                catch {
                                    console.error( scopeParams[ key ] + " $eval失败！" );
                                    vv = "";
                                }
                                requestParams[ key ] = vv;
                            }
                            options._requestParams = requestParams;
                            utils.autoDispatch( options, scope );
                        };
                    },
                };

            },
        };

    }]).directive('ngxLayuistar', ["layui", function (layui) {
        /**
         * layui评分展示
         * <div ngx-layuistar lay-options="{value: 5, readonly: true}"></div>
         */
        return {
            restrict: "A",
            link: function (scope, element, attr) {
                layui.rate.render({
                    elem: element[0],
                });
            },
        };
    }]).directive('ngxLayuiprogress', ["layui", function (layui) {
        /**
         * layui进度条
         * @see builder/test/controllers/WidgetController.php
         */
        var layElement = layui.element;
        return {
            restrict: "E",
            replace: true,
            template: `<div ng-class="['layui-progress', 'layui-progress-' + progressSize]" lay-showpercent="{{ layShowpercent }}">
                            <div ng-class="['layui-progress-bar', 'layui-bg-' + bgColor]" lay-percent="{{ value }}"></div>
                        </div>`,
            scope: {
                progressSize: "@", //大号进度条
                layShowpercent: "@", //显示进度值
                bgColor: "@", //进度条主题
                value: "@", //设置进度值
            },
            link: function (scope, element, attribute) {
                var ngModel = attribute.ngModel;
                var layFilter = attribute.layFilter;
                // 渲染
                layElement.render('progress', layFilter);

                // 动态赋值
                if (ngModel) {
                    // 动态设置percent
                    scope.$watch(function () {
                        return scope.$parent.$eval(ngModel);
                    }, function (newValue) {
                        if (newValue) {
                            layElement.progress(layFilter, newValue);
                        }
                    });
                }
            },
        };
    }]).directive('ngxLayuicarousel', ["layui", function (layui) {
        /**
         * layui轮播图
         * @see builder/test/controllers/WidgetController.php
         */
        var layCarousel = layui.carousel;
        return {
            restrict: "E",
            replace: true,
            scope: {
                options: "@",
                eventOnchange: "@",
            },
            transclude: true,
            template: `
                <div class="layui-carousel">
                    <div carousel-item ng-transclude>
                    </div>
                </div>
            `,
            link: function (scope, element, attribute) {
                var options = JSON.parse(scope.options);
                var onChange = scope.eventOnchange || '';

                options.elem = element.get(0);

                if (onChange) {
                    options.change = (new Function(onChange))();
                }

                // 渲染
                global.layCarousel || (global.layCarousel = {})
                global.layCarousel[options.id] = layCarousel.render(options)
            },
        };
    }]);
}(top, window, window.ym2App);